"""
自定义响应对象
"""
from lxml import etree
from bs4 import BeautifulSoup
import re
import json

class Response():
    def __init__(self, url, code, headers, request, body, meta):
        self.url = url
        self.code = code
        self.headers = headers
        self.request = request
        self.body = body

        self.meta = meta
    # xpath
    def xpath(self, rule):
        # 转换解析类型
        html_data = etree.HTML(self.body)
        # 调用xpath解析方法
        return html_data.xpath(rule)

    # bs4
    def select(self, selector):
        # 转换类型
        soup = BeautifulSoup(self.body, 'lxml')
        # 解析　select
        return soup.select(selector)

    # re
    def re_find(self, pattern):
        return re.findall(pattern, self.body)
    # json－－如果返回来的数据　是json字符串

    @property
    def json(self):
        try:
            data = json.loads(self.body.decode())
            return data

        except:
            return None